package com.ibm.pess.rest.resources;

import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.rest.common.api.ActivitiUtil;
import org.activiti.rest.common.api.SecuredResource;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Post;

import com.ibm.pess.order.Order;

public class NewOrderRestResource extends SecuredResource {

	private static Logger log = Logger.getLogger("log");

	@Post
	public Representation post(Representation entity) {
		JSONObject resp = new JSONObject();
		try {
			JsonRepresentation data = new JsonRepresentation(entity);
			JSONObject requestParms = data.getJsonObject();
			log.info("NewOrderRestResource requestParms:"
					+ requestParms.toString());

			Order order = createOrder();

			// launch a new order tracking process
			ProcessEngine pe = ActivitiUtil.getProcessEngine();
			Map<String, Object> variableMap = new HashMap<String, Object>();
			variableMap.put("process", "OrderTracking");
			variableMap.put("order", order);
			ProcessInstance processInstance = pe.getRuntimeService()
					.startProcessInstanceByKey("logistic-demo", variableMap);
		} catch (Exception e) {
			log.error("NewOrderRestResource error :" + e.toString());
			return new StringRepresentation(
					"{\"rc\":\"1\",\"reason\":\"empty in body\"}",
					MediaType.APPLICATION_JSON);
		}
		return new StringRepresentation(resp.toString(),
				MediaType.APPLICATION_JSON);
	}

	private Order createOrder() {
		Order od = new Order("Thinkpad Laptop", "BJ", "SH", "new", "foo",
				"bar", "Ring");

		return od;
	}
}
